const VERTEX_SHADER_SOURCE = `
  attribute vec4 a_Position;
  uniform float u_CosB;
  uniform float u_SinB;
  void main() {
    gl_Position.x = a_Position.x * u_CosB - a_Position.y * u_SinB;
    gl_Position.y = a_Position.x * u_SinB + a_Position.y * u_CosB;
    gl_Position.z = a_Position.z;
    gl_Position.w = 1.0;
  }
`;

const FRAGMENT_SHADER_SOURCE = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`;

const Angle = 90;
const main = () => {
  /** @type { WebGL2RenderingContext } */
  const gl = setupWebgl(document.querySelector("#root"));
  initShaders(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE);

  let n = initVertexBuffers(gl);
  if (n < 0) {
    console.error("Failed to set the positions of vertices.");
    return;
  }

  const rad = (Math.PI * Angle) / 180.0;
  const cosB = Math.cos(rad);
  const sinB = Math.sin(rad);

  const uCosB = gl.getUniformLocation(gl.program, "u_CosB");
  gl.uniform1f(uCosB, cosB);

  const uSinB = gl.getUniformLocation(gl.program, "u_SinB");
  gl.uniform1f(uSinB, sinB);

  // 设置清空颜色
  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.drawArrays(gl.TRIANGLES, 0, n);
};

const initVertexBuffers = (gl) => {
  let vertices = new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]);
  let n = 3;
  // 创建缓冲区对象
  let vertexBuffer = gl.createBuffer();

  if (!vertexBuffer) {
    console.error("Failed to create the buffer object.");
    return -1;
  }

  // 将缓冲区对象绑定到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 向缓冲区对象写入数据
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  // 获取 定点着色器中a_Position的引用或者指针
  const a_Position = gl.getAttribLocation(gl.program, "a_Position");
  // 讲当前缓冲区的数据分配给a_Position
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  // 开启定点着色器访问缓冲区数据
  gl.enableVertexAttribArray(a_Position);
  return n;
};
